<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card course-card">
          <template #header>
            <div class="card-header">
              <span>总课程数</span>
              <el-icon class="card-icon"><Document /></el-icon>
            </div>
          </template>
          <div class="card-body">
            <div class="number">{{ stats.courseCount || 0 }}</div>
            <div class="text">个课程</div>
<!--            <div class="trend">-->
<!--              <span class="trend-text">较昨日 +{{ getLastDayIncrease('course') }}</span>-->
<!--            </div>-->
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card teacher-card">
          <template #header>
            <div class="card-header">
              <span>总教师数</span>
              <el-icon class="card-icon"><User /></el-icon>
            </div>
          </template>
          <div class="card-body">
            <div class="number">{{ stats.teacherCount || 0 }}</div>
            <div class="text">名教师</div>
<!--            <div class="trend">-->
<!--              <span class="trend-text">较昨日 +{{ getLastDayIncrease('teacher') }}</span>-->
<!--            </div>-->
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card student-card">
          <template #header>
            <div class="card-header">
              <span>总学员数</span>
              <el-icon class="card-icon"><UserFilled /></el-icon>
            </div>
          </template>
          <div class="card-body">
            <div class="number">{{ stats.studentCount || 0 }}</div>
            <div class="text">名学员</div>
<!--            <div class="trend">-->
<!--              <span class="trend-text">活跃学员 {{ getActiveStudents() }}</span>-->
<!--            </div>-->
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card revenue-card">
          <template #header>
            <div class="card-header">
              <span>总营收</span>
              <el-icon class="card-icon"><Money /></el-icon>
            </div>
          </template>
          <div class="card-body">
            <div class="number">¥{{ formatMoney(stats.totalRevenue || 0) }}</div>
            <div class="text">总营收额</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>最近7天营收趋势</span>
              <el-button type="text" @click="refreshDailyRevenue">刷新</el-button>
            </div>
          </template>
          <div class="chart-container">
            <div v-if="dailyRevenue.dates && dailyRevenue.dates.length > 0" class="revenue-chart">
              <div class="chart-data">
                <div v-for="(date, index) in dailyRevenue.dates" :key="index" class="data-column">
                  <div class="date-label">{{ date }}</div>
                  <div class="revenue-bar">
                    <div
                      class="bar revenue-bar-fill"
                      :style="{ height: Math.max(25, (dailyRevenue.amounts?.[index] || 0) / maxDailyRevenue * 180) + 'px' }"
                    >
                      <span class="bar-value">¥{{ formatMoney(dailyRevenue.amounts?.[index] || 0) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="placeholder">暂无数据</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>月营收统计</span>
              <el-button type="text" @click="refreshMonthlyRevenue">刷新</el-button>
            </div>
          </template>
          <div class="chart-container">
            <div v-if="monthlyRevenue.months && monthlyRevenue.months.length > 0" class="monthly-chart">
              <div class="chart-data">
                <div v-for="(month, index) in monthlyRevenue.months" :key="index" class="month-item">
                  <div class="month-label">{{ month }}</div>
                  <div class="month-revenue">
                    <div
                      class="month-bar"
                      :style="{ width: Math.max(50, (monthlyRevenue.amounts?.[index] || 0) / maxMonthlyRevenue * 250) + 'px' }"
                    >
                    </div>
                    <span class="month-value-right">
                      ¥{{ formatMoney(monthlyRevenue.amounts?.[index] || 0) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="placeholder">暂无数据</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, User, UserFilled, Money } from '@element-plus/icons-vue'
import {
  getDashboardStats,
  getCourseCategoryStats,
  getRevenueStats,
  getDailyRevenue,
  getMonthlyRevenue
} from '@/api/dashboard'

// 基础统计数据
const stats = ref({
  courseCount: 0,
  teacherCount: 0,
  studentCount: 0,
  totalRevenue: 0
})

// 日营收数据
const dailyRevenue = ref({
  dates: [],
  amounts: []
})

// 月营收数据
const monthlyRevenue = ref({
  months: [],
  amounts: []
})

// 课程分类统计
const categoryStats = ref([])

// 计算分类统计的最大值（用于绘制图表）
const maxCategoryValue = computed(() => {
  if (categoryStats.value.length === 0) return 1
  return Math.max(...categoryStats.value.map(item => item.value))
})

// 计算日营收最大值
const maxDailyRevenue = computed(() => {
  if (!dailyRevenue.value.amounts || dailyRevenue.value.amounts.length === 0) return 1
  return Math.max(...dailyRevenue.value.amounts)
})

// 计算月营收最大值
const maxMonthlyRevenue = computed(() => {
  if (!monthlyRevenue.value.amounts || monthlyRevenue.value.amounts.length === 0) return 1
  return Math.max(...monthlyRevenue.value.amounts)
})

// 获取基础统计数据
const fetchStats = async () => {
  try {
    const { data } = await getDashboardStats()
    stats.value = data
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取日营收数据
const fetchDailyRevenue = async () => {
  try {
    const { data } = await getDailyRevenue()
    dailyRevenue.value = data
  } catch (error) {
    console.error('获取日营收数据失败:', error)
    ElMessage.error('获取日营收数据失败')
  }
}

// 获取月营收数据
const fetchMonthlyRevenue = async () => {
  try {
    const { data } = await getMonthlyRevenue()
    monthlyRevenue.value = data
  } catch (error) {
    console.error('获取月营收数据失败:', error)
    ElMessage.error('获取月营收数据失败')
  }
}

// 获取课程分类统计
const fetchCategoryStats = async () => {
  try {
    const { data } = await getCourseCategoryStats()
    categoryStats.value = data
  } catch (error) {
    console.error('获取课程分类统计失败:', error)
    ElMessage.error('获取课程分类统计失败')
  }
}

// 刷新方法
const refreshDailyRevenue = () => {
  fetchDailyRevenue()
}

const refreshMonthlyRevenue = () => {
  fetchMonthlyRevenue()
}

const refreshCategoryStats = () => {
  fetchCategoryStats()
}

// 格式化金额
const formatMoney = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 获取活跃学员数
const getActiveStudents = () => {
  return Math.floor((stats.value.studentCount || 0) * 0.8)
}

// 获取分类颜色
const getCategoryColor = (index) => {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  return colors[index % colors.length]
}

// 初始化数据
const initData = async () => {
  await Promise.all([
    fetchStats(),
    fetchDailyRevenue(),
    fetchMonthlyRevenue(),
    fetchCategoryStats()
  ])
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;

  .dashboard-card {
    transition: transform 0.3s;
    border-radius: 8px;

    &:hover {
      transform: translateY(-2px);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      color: #303133;

      .card-icon {
        font-size: 20px;
        opacity: 0.6;
      }
    }

    .card-body {
      text-align: center;
      padding: 20px 0;

      .number {
        font-size: 32px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .text {
        color: #909399;
        font-size: 14px;
        margin-bottom: 12px;
      }

      .trend {
        .trend-text {
          font-size: 12px;
          color: #67C23A;
        }
      }
    }
  }

  .course-card .number { color: #409EFF; }
  .teacher-card .number { color: #67C23A; }
  .student-card .number { color: #E6A23C; }
  .revenue-card .number { color: #F56C6C; }

  .chart-card {
    margin-top: 20px;

    .chart-container {
      height: 320px;
      padding: 15px;
      overflow: hidden;

      .placeholder {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #909399;
        font-size: 14px;
      }

      .revenue-chart {
        height: 100%;

        .chart-data {
          display: flex;
          justify-content: space-around;
          align-items: flex-end;
          height: calc(100% - 60px);
          padding: 40px 10px 20px 10px;
          overflow: visible;

          .data-column {
            display: flex;
            flex-direction: column;
            align-items: center;
            flex: 1;
            max-width: 80px;

            .date-label {
              font-size: 12px;
              color: #909399;
              margin-bottom: 10px;
              text-align: center;
              white-space: nowrap;
            }

            .revenue-bar {
              display: flex;
              align-items: flex-end;
              justify-content: center;
              width: 100%;

              .bar {
                width: 35px;
                min-height: 20px;
                border-radius: 4px 4px 0 0;
                background: linear-gradient(to top, #F56C6C, #FF8A8A);
                display: flex;
                align-items: flex-start;
                justify-content: center;
                position: relative;

                .bar-value {
                  position: absolute;
                  top: -32px;
                  left: 50%;
                  transform: translateX(-50%);
                  font-size: 11px;
                  color: #303133;
                  font-weight: 600;
                  white-space: nowrap;
                  text-align: center;
                  background: rgba(255, 255, 255, 0.95);
                  padding: 3px 6px;
                  border-radius: 4px;
                  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                  border: 1px solid rgba(0, 0, 0, 0.05);
                }
              }
            }
          }
        }
      }

      .category-chart {
        height: 100%;

        .category-item {
          display: flex;
          align-items: center;
          margin-bottom: 15px;

          .category-name {
            width: 80px;
            font-size: 14px;
            color: #303133;
          }

          .category-bar {
            flex: 1;
            height: 20px;
            background: #f5f7fa;
            border-radius: 10px;
            position: relative;
            margin: 0 10px;

            .bar-fill {
              height: 100%;
              border-radius: 10px;
              transition: width 0.3s;
            }
          }

          .category-value {
            width: 40px;
            text-align: right;
            font-size: 14px;
            font-weight: bold;
            color: #303133;
          }
        }
      }

      .monthly-chart {
        height: 100%;
        padding: 15px 10px;
        overflow: hidden;

        .chart-data {
          height: 100%;
          overflow-y: auto;

          .month-item {
            display: flex;
            align-items: center;
            margin-bottom: 18px;
            min-height: 35px;

            .month-label {
              width: 70px;
              font-size: 13px;
              color: #303133;
              text-align: right;
              margin-right: 15px;
              white-space: nowrap;
              flex-shrink: 0;
            }

            .month-revenue {
              flex: 1;
              display: flex;
              align-items: center;
              position: relative;
              min-width: 0;

              .month-bar {
                height: 28px;
                background: linear-gradient(to right, #67C23A, #85CE61);
                border-radius: 14px;
                min-width: 50px;
                transition: width 0.3s ease;
                margin-right: 12px;
              }

              .month-value-right {
                color: #303133;
                font-size: 12px;
                font-weight: 600;
                white-space: nowrap;
                background: rgba(255, 255, 255, 0.95);
                padding: 3px 8px;
                border-radius: 4px;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                border: 1px solid rgba(0, 0, 0, 0.05);
                flex-shrink: 0;
              }
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .dashboard {
    .chart-container {
      height: 280px;
      padding: 10px;
    }

    .revenue-chart .chart-data {
      padding: 30px 5px 15px 5px;

      .data-column {
        max-width: 60px;

        .bar-value {
          font-size: 10px;
          font-weight: 600;
          top: -28px;
          padding: 2px 5px;
        }
      }
    }

    .monthly-chart {
      .month-item {
        margin-bottom: 12px;
        min-height: 30px;

        .month-label {
          width: 60px;
          font-size: 12px;
        }

        .month-bar {
          height: 24px;
          margin-right: 10px;
        }

        .month-value-right {
          font-size: 11px;
          font-weight: 600;
          padding: 2px 6px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .dashboard {
    .chart-container {
      height: 250px;
      padding: 8px;
    }

    .revenue-chart .chart-data {
      .data-column {
        max-width: 45px;

        .date-label {
          font-size: 10px;
        }

        .bar {
          width: 25px;
        }

        .bar-value {
          font-size: 9px;
          font-weight: 600;
          padding: 2px 4px;
          top: -26px;
        }
      }
    }

    .monthly-chart {
      .month-item {
        margin-bottom: 10px;
        min-height: 25px;

        .month-label {
          width: 50px;
          font-size: 11px;
          margin-right: 10px;
        }

        .month-bar {
          height: 20px;
          margin-right: 8px;
        }

        .month-value-right {
          font-size: 10px;
          font-weight: 600;
          padding: 2px 5px;
        }
      }
    }
  }
}
</style>
